package com.example.mall.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.mall.common.api.CommonPage;
import com.example.mall.common.api.CommonResult;
import com.example.mall.dto.DataDto;
import com.example.mall.dto.ExcelDto;
import com.example.mall.dto.WeightDto;
import com.example.mall.mbg.model.*;
import com.example.mall.service.DataService;
import com.example.mall.service.IndicatorService;
import com.example.mall.service.SupplierService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * DataController
 * Created by on 2023/12/27.
 */
@Api(tags = "DataController", description = "数据管理")
@Controller
@RequestMapping("/data")
public class DataController {
    @Autowired
    private DataService dataService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private IndicatorService indicatorService;

    private static final Logger LOGGER = LoggerFactory.getLogger(DataController.class);

    @ApiOperation("画面：导入数据")
    @RequestMapping(value = {"upload"},method = {RequestMethod.GET})
    public String upload(Model model, HttpSession session) {
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "data-upload";
    }

    @ApiOperation("画面：数据列表")
    @RequestMapping(value = {"init"},method = {RequestMethod.GET})
    public String init(Model model, HttpSession session) {
        List<DataDto> dataDtos = new ArrayList<>();
        List<Data> dataList = dataService.listAll();
        dataList.forEach(data -> {
            DataDto dataDto = new DataDto(data);
            Supplier supplier = supplierService.get(data.getSupplierid());
            Indicator indicator = indicatorService.get(data.getIndicatorid());
            dataDto.setSupplier(supplier);
            dataDto.setIndicator(indicator);
            dataDtos.add(dataDto);
        });
        model.addAttribute("dataDtos", dataDtos);
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "data-list";
    }

    @ApiOperation("获取所有数据列表")
    @RequestMapping(value = "listAll", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<DataDto>> getDataList() {
        List<DataDto> dataDtos = new ArrayList<>();
        List<Data> dataList = dataService.listAll();
        dataList.forEach(data -> {
            DataDto dataDto = new DataDto(data);
            Supplier supplier = supplierService.get(data.getSupplierid());
            Indicator indicator = indicatorService.get(data.getIndicatorid());
            dataDto.setSupplier(supplier);
            dataDto.setIndicator(indicator);
            dataDtos.add(dataDto);
        });
        return CommonResult.success(dataDtos);
    }

    @ApiOperation("添加数据")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createData(@RequestBody Data data) {
        CommonResult commonResult;
        int count = dataService.create(data);
        if (count == 1) {
            commonResult = CommonResult.success(data);
            LOGGER.debug("createData success:{}", data);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("createData failed:{}", data);
        }
        return commonResult;
    }

    @ApiOperation("画面：指标库编辑")
    @RequestMapping(value = {"edit"},method = {RequestMethod.GET})
    public String edit(Model model, Integer dataid, HttpSession session) {
        Data data = dataService.get(dataid);
        List<Supplier> supplierList = supplierService.listAll();
        List<Indicator> indicatorList = indicatorService.listAll();
        model.addAttribute("data", data);
        model.addAttribute("supplierList", supplierList);
        model.addAttribute("indicatorList", indicatorList);
        Object user1 = session.getAttribute("user");
        if (user1 != null) {
            model.addAttribute("user", user1);
        }
        return "data-detail";
    }

    @ApiOperation("更新指定id数据信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateData(@PathVariable("id") Integer dataid, @RequestBody Data data, BindingResult bindingResult) {
        CommonResult commonResult;
        data.setUpdatetime(new Date());
        int count = dataService.update(dataid, data);
        if (count == 1) {
            commonResult = CommonResult.success(data);
            LOGGER.debug("updateData success:{}", data);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("updateData failed:{}", data);
        }
        return commonResult;
    }

    @ApiOperation("删除指定id的数据")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteData(@PathVariable("id") Integer dataid) {
        CommonResult commonResult;
        int count = dataService.delete(dataid);
        if (count == 1) {
            commonResult = CommonResult.success(null);
            LOGGER.debug("deleteData success:id={}", dataid);
        } else {
            commonResult = CommonResult.failed("操作失败");
            LOGGER.debug("deleteData failed:id={}", dataid);
        }
        return commonResult;
    }

    @ApiOperation("分页查询数据列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<Data>> listData(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
        List<Data> dataList = dataService.list(pageNum, pageSize);
        return CommonResult.success(CommonPage.restPage(dataList));
    }

    @ApiOperation("获取指定id的数据详情")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Data> data(@PathVariable("id") Integer dataid) {
        return CommonResult.success(dataService.get(dataid));
    }

    @ApiOperation("数据备份")
    @RequestMapping(value = "exportFile", method = RequestMethod.GET)
    public void exportFile(HttpServletResponse response) throws IOException {
        List<ExcelDto> excelDtoList = new ArrayList<>();
        List<Data> dataList = dataService.listAll();
        dataList.forEach(data -> {
            ExcelDto excelDto = new ExcelDto();
            Supplier supplier = supplierService.get(data.getSupplierid());
            Indicator indicator = indicatorService.get(data.getIndicatorid());
            excelDto.setSuppliername(supplier.getSuppliername());
            excelDto.setIndicatorname(indicator.getIndicatorname());
            excelDto.setDataname(data.getDataname());
            excelDto.setPeriod(data.getPeriod());
            excelDto.setValue(data.getValue());
            excelDtoList.add(excelDto);
        });
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("绩效数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream())
                .head(ExcelDto.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("绩效数据")
                .doWrite(excelDtoList);

    }

    @ApiOperation("数据恢复")
    @RequestMapping(value = "importFile", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<Data>> importFile(@RequestParam("file") MultipartFile excel) throws IOException {
        List<Data> dataList = new ArrayList<>();
        List<ExcelDto> excelDtoList = EasyExcel.read(excel.getInputStream())
                .head(ExcelDto.class)
                .sheet()
                .doReadSync();
        dataService.deleteAll();
        excelDtoList.forEach(excelDto -> {
            Data data = new Data();
            Supplier supplier = supplierService.getSupplierByName(excelDto.getSuppliername());
            Indicator indicator = indicatorService.getIndicatorByName(excelDto.getIndicatorname());
            data.setDataid(dataService.getNextId());
            data.setSupplierid(supplier.getSupplierid());
            data.setIndicatorid(indicator.getIndicatorid());
            data.setPeriod(excelDto.getPeriod());
            data.setDataname(excelDto.getDataname());
            data.setValue(excelDto.getValue());
            data.setDatasource("Excel导入");
            data.setCreatetime(new Date());
            data.setUpdatetime(new Date());
            dataList.add(data);
            dataService.create(data);
        });

        return CommonResult.success(dataList);
    }


}
